<template>
    <div>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="类型">
          <el-input v-model="queryForm.kw" placeholder="名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="list">
        <!-- <el-table-column label="序号" type="index" width="100" /> -->
        <el-table-column align="center" label="" width="100">
            <template #default="scope">
              <el-avatar shape="square" size="medium" :src="scope.row.pic"></el-avatar>
            </template>
        </el-table-column>
        <!-- <el-table-column label="发布时间" align="center" prop="createTime">
            <template #default="scope">
                <div>{{timestampToDayHM(scope.row.publishTime)}}</div>
            </template>
        </el-table-column> -->
        <el-table-column label="排序" align="center" prop="sort" width="80"/>
        <el-table-column label="分类名称" align="center" prop="name" />
        <el-table-column label="简要描述" align="center" prop="shortDesc" show-overflow-tooltip/>
        <el-table-column label="状态" align="center" prop="isDelete">
            <template #default="scope">
                <el-tag type="success" v-if="scope.row.isDelete==1">正常</el-tag>
                <el-tag type="info" v-if="scope.row.isDelete==-1">已下架</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.categoryId)" v-if="scope.row.isDelete==1">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row.categoryId)" v-if="scope.row.isDelete==1">删除</el-button>
            <el-button link type="success" icon="Check" @click="handleDelete2(scope.row.categoryId)" v-if="scope.row.isDelete==-1">恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getList" />
  
      <!-- 添加或修改参数配置对话框 -->
      <el-dialog v-model="open" :title="title" width="700px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="类别名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="简单描述" prop="shortDesc">
            <el-input v-model="form.shortDesc" placeholder="请输入分类描述" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" type="number" placeholder="数值越小越靠前" />
          </el-form-item>
          <el-form-item label="展示图" prop="role">
            <el-upload 
              class="avatar-uploader showUploader"
              ref="businessLicense"
              action
              :auto-upload="false"
              :show-file-list="false"
              :on-remove="handleRemoveLogo"
              :on-change="uploadLogoFile"
            >
            <ul class="img-list">
              <li v-if="form.pic==''" class="addpic"><el-icon><Plus/></el-icon></li>
            </ul>
            </el-upload>
            <ul class="img-list" v-if="form.pic!=''">
              <li class="img-li">
                <img :src="form.pic" class="avatar aspect-fill" style="width: 250px;height: 180px;" />
                <i class="logo-remove el-icon-delete" @click="handleRemoveLogo"><el-icon><Delete /></el-icon></i>
              </li>
            </ul>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  <script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { fileUploader } from '@/utils/upload.js'
  import { timestampToDayHM, timestampToHM, formatAmount } from "@/utils/utils"
  
  // 查询参数
  const queryForm = reactive({
    kw: "",
    pageNo: 1,
    pageSize: 10
  });
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);
  // 列表返回值
  const list = ref<any[]>([]);
  
  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  // 弹出框标题
  const title = ref("");
  // 提交表单数据
  let form = toRef(
    reactive({
      categoryId: "",
      name: "",
      pic: "",
      sort: '',
      isDelete: 1,
      shortDesc: "",
    })
  );
  // 表单验证
  const rules = ref({
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    shortDesc: [{ required: true, message: "商品描述不能为空", trigger: "blur" }],
  });
  
  /**
   * 查询列表
   */
  const getList = () => {
    loading.value = true;
    baseService
      .get("/admin/product/category/list", queryForm)
      .then((res) => {
        loading.value = false;
        if (res.code === 200) {
          list.value = res.data.records;
          total.value = res.data.totalrecord;
        } else {
          list.value = [];
        }
      }).catch(() => {
        loading.value = false;
      });
  };
  
  /**
   * 搜索按钮操作
   */
  function handleQuery() {
    queryForm.pageNo = 1;
    getList();
  }
  
  /**
   * 表单重置
   */
  function reset() {
    form.value = {
      categoryId: "",
      name: "",
      pic: "",
      sort: '',
      isDelete: 1,
      shortDesc: "",
    };
  
    nextTick(() => {
      formRef.value?.resetFields();
    });
  }
  
  /**
   * 新增按钮操作
   */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加";
  }
  
  /**
   * 修改按钮操作
   * @param id 主键
   */
  function handleUpdate(id: string) {
    open.value = true;
    title.value = "修改";
    reset();
    baseService.get(`/admin/product/category/info/${id}`).then((res) => {
      if (res.code === 200) {
        form.value = res.data;
      }
    });
  }
  
  /**
   * 提交按钮
   */
  function submitForm() {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return;
      baseService.post(`/admin/product/category/save`, form.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          open.value = false;
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }
  
  /**
   * 删除按钮操作
   * @param id 主键
   */
  function handleDelete(id: any) {
    ElMessageBox.confirm("确认要删除当前项吗?", "提示").then(() => {
      baseService.get(`/admin/product/category/delete/${id}`, id).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }
  function handleDelete2(id: any) {
    ElMessageBox.confirm("确认要恢复该分类吗?", "提示").then(() => {
      baseService.get(`/admin/product/category/rec/${id}`, id).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }

    // 上传LOGO图片
    function uploadLogoFile(file: any){
    const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
    const isJPG = typeArr.indexOf(file.raw.type) !== -1;
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isJPG) {
      // ElMessage.error("只能是图片!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    if (!isLt3M) {
      // ElMessage.error("上传图片大小不能超过 3MB!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    var formData = new FormData();
    formData.append("myFile", file.raw)
    fileUploader(formData).then((res) => {
      console.log('LOGO上传成功', res)
      if (res.data.errno==0) {
        form.value.pic=res.data.data[0]
      } else {
        // ElMessage.error(res.data.message);
      }
    })
  }
  // 移除LOGO图片
  function handleRemoveLogo(file: any){
    form.value.pic=''
    console.log('移除LOGO图片！',form.value.pic)
  }
  
  getList();
  </script>
  
<style scoped>
.addpic{
  font-size: 22px;
  padding: 20px 25px 15px 25px;
  border: 2px dashed #ccc;
  color: #888;
  height: 68px;
}
.img-list{
  display: flex;
  flex-wrap: wrap;
}
.img-list .img-li{
  width: 260px;
  position: relative;
  margin-right: 10px;
}
.logo-remove{
  font-size: 22px;
  position: absolute;
  top: 10px;
  right: 10px;
  color: #f00;
  cursor: pointer;
  text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
  box-shadow: #fff 3px 5px 6px;
  background-color: #fff;
}
.logo-remove:HOVER{
  color: #F56C6C;
}
</style>
  